package com.bro.person.admin.controller;

import com.bro.person.admin.service.ISecurityService;
import com.bro.person.admin.struct.AdminMenuStruct;
import com.bro.person.admin.struct.SecurityAuthenticateResultStruct;
import com.bro.person.admin.struct.SecurityUserStruct;
import com.bro.person.admin.utils.ValidateModelUtil;
import com.bro.person.base.constants.ConstConfig;
import com.bro.person.base.enums.error.GlobalEnum;
import com.bro.person.base.utils.ResponseBuilderUtil;
import com.bro.person.base.vo.ResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author swallow
 * Created by swallow on 2018/11/12.<br>
 */
@RestController
public class AuthController implements InitializingBean {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private ISecurityService securityService;

    @Override
    public void afterPropertiesSet() {
        Assert.notNull(securityService, "securityService can't be null");
    }

    /**
     * 简单设计的login
     */
    @PostMapping("/login")
    public ResultVO login(HttpServletRequest request, HttpServletResponse response,
                          @RequestParam(value = "username", required = false) String username,
                          @RequestParam(value = "password", required = false) String password) {
        logger.debug("[IndexController][login] entering request:{},response:{},username:{},password:{}", request,
                response, username, password);
        SecurityAuthenticateResultStruct authenticate;
        try {
            //用户认证 默认不是为空的 约定
            authenticate = securityService.authenticate(username, password);
            if(authenticate==null){
                return ResponseBuilderUtil.buildErrorJSON(GlobalEnum.BRO_UNAUTHORIZED_ERROR);
            }
            SecurityUserStruct user = authenticate.getUser();
            if(GlobalEnum.BRO_AUTHORIZED_SUCCESS.getCode()!=authenticate.getGlobalEnum().getCode()){
                // 用户认证不通过
                return ResponseBuilderUtil.buildErrorJSON(authenticate.getGlobalEnum());
            }
            //写入session
            HttpSession session = request.getSession();
            session.setAttribute(ConstConfig.SECURITY_USER_SESSION_KEY, user);
            session.setMaxInactiveInterval(ConstConfig.SECURITY_USER_SESSION_INVALID_TIME);
            //构建返回数据
            Map<String,Object> resultVO = new HashMap<>();
            resultVO.put("user",authenticate.getUser());
            resultVO.put("permissionList",authenticate.getPermissionList());
            return ResponseBuilderUtil.buildSuccessJson(resultVO);
        } catch (Exception e) {
            logger.error("[IndexController][login] errordesc request:{},response:{},username:{},password:{},e:{}",
                    request, response, username, password, e.getMessage());
            return ResponseBuilderUtil.buildErrorJSON(GlobalEnum.BRO_UNAUTHORIZED_ERROR);
        }
    }

    /**
     * 目前的目录api 以后会更改
     * @param request
     * @param response
     * @return
     */
    @GetMapping(value = "/sys/menu")
    public ResultVO getMenus(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        logger.debug("[AuthController][getMenus] entering request:{},response:{}",request, response);
        SecurityUserStruct securityUserStruct = (SecurityUserStruct)session.getAttribute(ConstConfig.SECURITY_USER_SESSION_KEY);
        List<AdminMenuStruct> adminMenuStructList = null;
        try {
            adminMenuStructList = securityService.queryNavResources(securityUserStruct.getUserId());
            if(adminMenuStructList==null){
                adminMenuStructList = new ArrayList<>();
            }
            logger.info("[AuthController][getMenus] desc request:{},response:{}",request, response);
            return ResponseBuilderUtil.buildSuccessJson(adminMenuStructList);
        } catch (Exception e) {
            logger.error("[AuthController][getMenus] errordesc request:{},response:{},errorMessage:{}",request, response, e.getMessage());
            return ResponseBuilderUtil.buildErrorJSON();
        }
    }
}
